<template>
  <div class="marketplace-container">
    <div class="marketplace-header">
      <h1 class="marketplace-title">应用市场</h1>
      <div class="marketplace-search">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索应用"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <div class="marketplace-content">
      <!-- 过滤和排序 -->
      <div class="filter-sort-container">
        <div class="category-filter">
          <el-radio-group v-model="selectedCategory" @change="handleCategoryChange">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button 
              v-for="category in categories" 
              :key="category.id" 
              :label="category.id"
            >
              {{ category.name }}
            </el-radio-button>
          </el-radio-group>
        </div>
        
        <div class="sort-options">
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
            <el-option label="最新发布" value="newest" />
            <el-option label="最多下载" value="downloads" />
            <el-option label="最高评分" value="rating" />
          </el-select>
        </div>
      </div>

      <!-- 应用列表 -->
      <div class="app-list" v-loading="loading">
        <el-empty v-if="filteredApps.length === 0" description="暂无应用" />
        
        <div class="app-grid">
          <div 
            v-for="app in filteredApps" 
            :key="app.id" 
            class="app-card"
            @click="showAppDetail(app)"
          >
            <div class="app-icon">
              <img :src="app.icon" :alt="app.name" />
            </div>
            <div class="app-info">
              <h3 class="app-name">{{ app.name }}</h3>
              <p class="app-description">{{ app.description }}</p>
              <div class="app-meta">
                <span class="app-developer">{{ app.developerName }}</span>
                <span class="app-downloads">{{ formatDownloads(app.views) }}</span>
              </div>
              <div class="app-actions">
                <el-button 
                  v-if="isAppInstalled(app.id)"
                  type="primary"
                  size="small"
                  @click.stop="openApp(app.id)"
                >
                  打开
                </el-button>
                <el-button 
                  v-else
                  type="primary"
                  size="small"
                  @click.stop="installApp(app)"
                >
                  安装
                </el-button>
                <el-button 
                  type="default"
                  size="small"
                  @click.stop="showAppDetail(app)"
                >
                  详情
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 应用详情对话框 -->
    <el-dialog
      v-model="appDetailVisible"
      :title="selectedApp?.name"
      width="800px"
      destroy-on-close
    >
      <div v-if="selectedApp" class="app-detail">
        <div class="app-detail-header">
          <div class="app-detail-icon">
            <img :src="selectedApp.icon" :alt="selectedApp.name" />
          </div>
          <div class="app-detail-info">
            <h2>{{ selectedApp.name }}</h2>
            <p class="developer">开发者：{{ selectedApp.developerName }}</p>
            <p class="version">版本：{{ selectedApp.version }}</p>
            <p class="downloads">下载量：{{ formatDownloads(selectedApp.views) }}</p>
            <div class="actions">
              <el-button 
                v-if="isAppInstalled(selectedApp.id)"
                type="primary"
                @click="openApp(selectedApp.id)"
              >
                打开
              </el-button>
              <el-button 
                v-else
                type="primary"
                @click="installApp(selectedApp)"
              >
                安装
              </el-button>
              <el-button 
                v-if="isAppInstalled(selectedApp.id)"
                type="danger"
                @click="uninstallApp(selectedApp.id)"
              >
                卸载
              </el-button>
            </div>
          </div>
        </div>
        
        <div class="app-detail-content">
          <h3>应用介绍</h3>
          <p>{{ selectedApp.description }}</p>
          
          <template v-if="selectedApp.screenshots && selectedApp.screenshots.length > 0">
            <h3>应用截图</h3>
            <el-carousel :interval="4000" type="card" height="300px">
              <el-carousel-item v-for="(screenshot, index) in selectedApp.screenshots" :key="index">
                <img :src="screenshot" :alt="selectedApp.name + ' 截图'" />
              </el-carousel-item>
            </el-carousel>
          </template>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getAppList } from '@/api/app'
import { getAppCategoryList } from '@/api/category'
import { useAppStore } from '@/stores/app'
import type { App, AppCategory } from '@/types/app'

interface AppResponse {
  list: App[];
  total: number;
}

// 应用商店
const appStore = useAppStore()

// 加载状态
const loading = ref(false)

// 应用列表
const appList = ref<App[]>([])

// 分类列表
const categories = ref<AppCategory[]>([])

// 搜索关键词
const searchKeyword = ref('')

// 选中的分类
const selectedCategory = ref('')

// 排序方式
const sortBy = ref('newest')

// 分页
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 应用详情
const appDetailVisible = ref(false)
const selectedApp = ref<App | null>(null)

// 过滤后的应用列表
const filteredApps = computed(() => {
  let result = appList.value

  // 按分类过滤
  if (selectedCategory.value) {
    result = result.filter(app => app.categoryId === Number(selectedCategory.value))
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(app => 
      app.name.toLowerCase().includes(keyword) || 
      app.description.toLowerCase().includes(keyword) ||
      app.developerName.toLowerCase().includes(keyword)
    )
  }

  // 排序
  result = [...result].sort((a, b) => {
    switch (sortBy.value) {
      case 'downloads':
        return (b.views || 0) - (a.views || 0)
      case 'rating':
        // TODO: 添加评分功能
        return 0
      case 'newest':
      default:
        return new Date(b.updatedAt || '').getTime() - new Date(a.updatedAt || '').getTime()
    }
  })

  return result
})

// 获取应用列表
const fetchAppList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      status: 1 // 已发布
    }
    const { data } = await getAppList(params)
    const response = data as AppResponse
    appList.value = response.list
    total.value = response.total
  } catch (error) {
    console.error('获取应用列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await getAppCategoryList()
    categories.value = res
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 检查应用是否已安装
const isAppInstalled = (appId: number) => {
  return appStore.installedApps.some(app => app.id === appId)
}

// 安装应用
const installApp = async (app: App) => {
  try {
    await appStore.installApp(app)
    ElMessage.success('应用安装成功')
  } catch (error) {
    console.error('应用安装失败:', error)
    ElMessage.error('应用安装失败')
  }
}

// 卸载应用
const uninstallApp = async (appId: number) => {
  try {
    await appStore.uninstallApp(appId)
    ElMessage.success('应用卸载成功')
    appDetailVisible.value = false
  } catch (error) {
    console.error('应用卸载失败:', error)
    ElMessage.error('应用卸载失败')
  }
}

// 打开应用
const openApp = async (appId: number) => {
  try {
    await appStore.openApp(appId)
    appDetailVisible.value = false
  } catch (error) {
    console.error('打开应用失败:', error)
    ElMessage.error('打开应用失败')
  }
}

// 显示应用详情
const showAppDetail = (app: App) => {
  selectedApp.value = app
  appDetailVisible.value = true
}

// 格式化下载量
const formatDownloads = (downloads: number = 0) => {
  if (downloads >= 1000000) {
    return (downloads / 1000000).toFixed(1) + 'M'
  } else if (downloads >= 1000) {
    return (downloads / 1000).toFixed(1) + 'K'
  } else {
    return downloads.toString()
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchAppList()
}

// 处理分类变更
const handleCategoryChange = () => {
  currentPage.value = 1
  fetchAppList()
}

// 处理排序变更
const handleSort = () => {
  currentPage.value = 1
  fetchAppList()
}

// 处理页码变更
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchAppList()
}

// 处理每页数量变更
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchAppList()
}

// 组件挂载时
onMounted(() => {
  fetchAppList()
  fetchCategories()
})
</script>

<style scoped>
.marketplace-container {
  width: 100%;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.marketplace-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.marketplace-title {
  font-size: 1.5rem;
  margin: 0;
}

.marketplace-search {
  width: 300px;
}

.marketplace-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.filter-sort-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.category-filter {
  flex: 1;
}

.sort-options {
  margin-left: 20px;
}

.app-list {
  min-height: 400px;
}

.app-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.app-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
  display: flex;
  flex-direction: column;
}

.app-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.app-icon {
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
}

.app-icon img {
  max-width: 80px;
  max-height: 80px;
  object-fit: contain;
}

.app-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.app-name {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 500;
}

.app-description {
  margin: 0 0 15px;
  font-size: 14px;
  color: #606266;
  flex: 1;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.app-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
  margin-bottom: 10px;
}

.app-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 应用详情样式 */
.app-detail {
  padding: 20px;
}

.app-detail-header {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.app-detail-icon {
  width: 120px;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.app-detail-icon img {
  max-width: 80px;
  max-height: 80px;
  object-fit: contain;
}

.app-detail-info {
  flex: 1;
}

.app-detail-info h2 {
  margin: 0 0 10px;
  font-size: 24px;
}

.app-detail-info p {
  margin: 5px 0;
  color: #606266;
}

.app-detail-info .actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.app-detail-content {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.app-detail-content h3 {
  margin: 20px 0 10px;
  font-size: 18px;
}

.app-detail-content p {
  color: #606266;
  line-height: 1.6;
}

:deep(.el-carousel__item img) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style> 